<!-- 修改邮箱弹窗 -->
<script lang="tsx">
import { defineComponent, ref, computed, reactive, nextTick } from 'vue';
import { $t } from '@vben/locales';
import { ElMessage } from 'element-plus';
import { getEmailCodeApi } from '#/api/core/auth';
import { verifyUserEmailApi, updateUserEmailApi } from '#/api/system/user';
import { EmailMatcher } from '#/utils/constants';

export default defineComponent({
  name: 'ChangeEmailDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    currentEmail: {
      type: String,
      default: '',
    },
  },
  emits: ['update:modelValue', 'confirm'],
  setup(props, { emit }) {
    const formRef = ref();
    const loading = ref(false);
    // 当没有旧邮箱时，直接从第二步开始
    const currentStep = ref(props.currentEmail ? 1 : 2); // 当没有旧邮箱时，直接从第二步开始

    // 验证码倒计时
    const countdown = ref(0);
    const isCounting = computed(() => countdown.value > 0);

    // 表单数据
    const form = reactive({
      oldEmailCode: '', // 旧邮箱验证码
      newEmail: '', // 新邮箱
      newEmailCode: '', // 新邮箱验证码
    });

    const visible = computed({
      get: () => props.modelValue,
      set: (val: boolean) => emit('update:modelValue', val)
    });

    // 表单验证规则
    const rules = computed(() => ({
      oldEmailCode: [
        { required: true, message: $t('personal.pleaseEnterVerifyCode'), trigger: 'blur' }
      ],
      newEmail: [
        { required: true, pattern: EmailMatcher, message: $t('common.emailPhTxt'), trigger: 'blur' }
      ],
      newEmailCode: [
        { required: true, message: $t('personal.pleaseEnterVerifyCode'), trigger: 'blur' }
      ],
    }));

    // 开始倒计时
    const startCountdown = (seconds: number = 60) => {
      countdown.value = seconds;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    };

    // 获取验证码
    const getCode = async () => {
      if (isCounting.value) return;

      if (props.currentEmail && currentStep.value === 1) {
        // 第一步：验证旧邮箱，直接发送验证码
        try {
          startCountdown();
          await getEmailCodeApi({ email: props.currentEmail });
          ElMessage.success($t('personal.smsCodeSent'));
        } catch (error: any) {
        }
      } else {
        // 第二步：验证新邮箱
        formRef.value?.validateField('newEmail', async (valid: boolean) => {
          if (valid) {
            try {
              startCountdown();
              await getEmailCodeApi({ email: form.newEmail });
              ElMessage.success($t('personal.smsCodeSent'));
            } catch (error: any) {
            }
          } else {
            console.log('邮箱验证失败，不发送验证码');
            ElMessage.warning($t('personal.pleaseEnterCorrectEmail'));
          }
        });
      }
    };

    // 关闭弹窗
    const handleClose = () => {
      visible.value = false;
      // 重置表单和状态
      currentStep.value = props.currentEmail ? 1 : 2;
      form.oldEmailCode = '';
      form.newEmail = '';
      form.newEmailCode = '';
      countdown.value = 0;
      formRef.value?.resetFields();
    };

    // 验证旧邮箱 - 第一步
    const verifyOldEmail = async () => {
      try {
        loading.value = true;
        formRef.value?.validateField('oldEmailCode', async (valid: boolean) => {
          if (valid) {
            console.log('验证成功')
            // 调用验证旧邮箱API
            const data = {
              email: props.currentEmail,
              verificationCode: form.oldEmailCode,
            };

            console.log(data, 'data')

            await verifyUserEmailApi(data);

            ElMessage.success($t('personal.oldEmailVerifiedSuccess'));
            currentStep.value = 2;

            // 重置验证码倒计时
            countdown.value = 0;

            // 清空新邮箱相关字段
            form.newEmail = '';
            form.newEmailCode = '';

            // 清空旧邮箱验证码
            form.oldEmailCode = '';

            // 等待DOM更新后清除验证
            await nextTick();
            formRef.value?.clearValidate(['newEmail', 'newEmailCode']);
          } else {
            console.log('验证失败')
          }
        });
      } catch (error: any) {
      } finally {
        loading.value = false;
      }
    };

    // 确认修改邮箱 - 第二步
    const handleConfirm = async () => {
      if (props.currentEmail && currentStep.value === 1) {
        await verifyOldEmail();
        return;
      }

      try {
        loading.value = true;

        // 验证表单字段
        await new Promise((resolve, reject) => {
          formRef.value?.validate((valid: boolean) => {
            if (valid) {
              resolve(true);
            } else {
              reject(new Error('validation failed'));
            }
          });
        });

        // 调用修改邮箱API
        const data = {
          email: form.newEmail,
          verificationCode: form.newEmailCode,
        };

        console.log(data, 'data')

        await updateUserEmailApi(data);

        ElMessage.success($t('personal.emailChangedSuccess'));
        emit('confirm', { newEmail: data.email });
        handleClose();

      } catch (error: any) {
      } finally {
        loading.value = false;
      }
    };

    const isSumbit = computed(() => {
      if (props.currentEmail && currentStep.value === 1) {
        // 第一步：只需要旧邮箱验证码
        const result = !form.oldEmailCode.trim();
        return result;
      } else {
        // 第二步：需要新邮箱和新邮箱验证码
        const result = !form.newEmail.trim() || !form.newEmailCode.trim();
        return result;
      }
    })

    return () => (
      <el-dialog
        v-model={visible.value}
        title={props.currentEmail
          ? (currentStep.value === 1 ? $t('personal.verifyOldEmail') : $t('personal.changeEmail'))
          : $t('personal.changeEmailNoOldEmail')}
        width="450px"
        onClose={handleClose}
        append-to-body
        destroy-on-close
        close-on-click-modal={false}
        class="change-email-dialog"
        v-slots={{
          footer: () => (
            <div class="flex justify-end">
              <el-button onClick={handleClose}>{$t('common.cancel')}</el-button>
              <el-button
                type="primary"
                onClick={handleConfirm}
                disabled={isSumbit.value}
                loading={loading.value}
              >
                {$t('common.confirm')}
              </el-button>
            </div>
          )
        }}
      >
        <div>
          <div class={['text-right', 'text-sm', 'mb-[10px]', currentStep.value === 2 ? 'text-[#0067D1]' : 'text-[#595959]']}>
            {props.currentEmail
              ? (currentStep.value === 1
                ? $t('personal.verifyOldEmailTip')
                : $t('personal.emailSecurityTip'))
              : $t('personal.emailSecurityTipNoOldEmail')}
          </div>

          <el-form
            ref={formRef}
            model={form}
            rules={rules.value}
            label-width="66px"
            label-position="right"
          >
            {props.currentEmail && currentStep.value === 1 ? (
              // 第一步：验证旧邮箱
              <>
                <el-form-item label={$t('personal.originalEmail')}>
                  <el-input
                    value={props.currentEmail}
                    maxlength={255}
                    disabled
                    class="disabled-input"
                  />
                </el-form-item>

                <el-form-item label={$t('personal.verificationCode')} prop="oldEmailCode">
                  <el-input
                    v-model={form.oldEmailCode}
                    placeholder={$t('personal.pleaseEnterVerifyCode')}
                    maxlength={6}
                    minlength={3}
                    v-slots={{
                      append: () => (
                        <el-button
                          type="primary"
                          disabled={isCounting.value}
                          onClick={getCode}
                        >
                          <span class="text-[#0067D1]">
                            {isCounting.value ? `${countdown.value}s后重试` : $t('personal.getVerifyCode')}
                          </span>
                        </el-button>
                      )
                    }}
                  />
                </el-form-item>
              </>
            ) : (
              // 第二步：绑定新邮箱
              <>
                <el-form-item label={$t('personal.newEmail')} prop="newEmail">
                  <el-input
                    v-model={form.newEmail}
                    placeholder={$t('personal.pleaseEnterNewEmail')}
                    clearable
                    maxlength={255}
                  />
                </el-form-item>

                <el-form-item label={$t('personal.verificationCode')} prop="newEmailCode">
                  <el-input
                    v-model={form.newEmailCode}
                    placeholder={$t('personal.pleaseEnterVerifyCode')}
                    maxlength={6}
                    minlength={3}
                    v-slots={{
                      append: () => (
                        <el-button
                          type="primary"
                          disabled={isCounting.value}
                          onClick={getCode}
                        >
                          <span class={form.newEmail ? 'text-[#0067D1]' : ''}>
                            {isCounting.value ? `${countdown.value}s` : $t('personal.getVerifyCode')}
                          </span>
                        </el-button>
                      )
                    }}
                  />
                </el-form-item>
              </>
            )}
          </el-form>
        </div>
      </el-dialog>
    );
  },
});
</script>

<style>
.change-email-dialog :deep(.el-form-item .el-form-item__label) {
  @apply pb-2 font-medium;
}

.change-email-dialog :deep(.el-form-item .el-form-item__content) {
  @apply flex-1;
}

.change-email-dialog :deep(.disabled-input .el-input__inner) {
  background-color: #f5f7fa;
  color: #909399;
}

/* 确保输入框组合样式一致 */
.change-email-dialog :deep(.el-input-group__append) {
  border: 1px solid var(--el-input-border-color);
  border-left: 0;
}
</style>
